'use strict'

import { app, BrowserWindow, ipcMain } from 'electron'
import path from 'path'
import FormData from 'form-data'
import fs from 'fs'
import axios from 'axios'

const server = axios.create({
  baseURL: 'http://127.0.0.1:9092',
  headers: { 'X-Custom-Header': 'foobar' },
  maxContentLength: Infinity
})

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path')
    .join(__dirname, '/static')
    .replace(/\\/g, '\\\\')
}

let mainWindow
const winURL =
  process.env.NODE_ENV === 'development'
    ? `http://localhost:9080`
    : `file://${__dirname}/index.html`

function createWindow () {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    height: 563,
    useContentSize: true,
    width: 1000
  })

  mainWindow.loadURL(winURL)

  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

ipcMain.on('asynchronous-message', (e, params) => {
  const { index, filePath } = params
  console.log(index, filePath)
  const form = new FormData()
  form.append('file', fs.createReadStream(path.join(filePath)))

  server.post('/demo', form, {
    headers: form.getHeaders()
  })
    .then((res) => {
      console.log('upload success :)')
      const { code } = res.data
      e.sender.send('asynchronous-reply', { index, code })
    })
    .catch((error) => {
      console.log('Something went wrong :(')
      console.error(error)
      e.sender.send('asynchronous-reply', { index, code: 1 })// 失败码
    })
})
